#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <pthread.h>
#pragma comment(lib,"ws2_32.lib")

#define MY_PORT 165226
#define DEST_IP "10.1.1.232"
int main()
{
    SOCKET con_socket;
    struct sockaddr_in remote_addr;
    char buffer[1024];
    char file_name[100];
    char readch;
    int i;

    WSADATA wsaDate;

    WSAStartup(MAKEWORD(1,1),&wsaDate);

    memset(file_name,0,sizeof(file_name));
    memset(buffer,0,sizeof(buffer));

    remote_addr.sin_family=AF_INET;
    remote_addr.sin_port=htons(MY_PORT);
    remote_addr.sin_addr.s_addr=inet_addr(DEST_IP);

    con_socket=socket(AF_INET,SOCK_STREAM,0);
    if(con_socket==-1)
    {
        printf("Client socket failed!");
        exit(0);
    }

    printf("Please Input File Name:\n");
    scanf("%s", file_name);

    if(connect(con_socket,(struct sockaddr*)&remote_addr,sizeof(struct sockaddr))==-1)
    {
        printf("Client connet failed!");
    }
    else
    {
        FILE *fp=fopen(file_name,"r");
        if(fp==NULL)
        {
            printf("%s File not Found!\n",file_name);
        }
        else
        {
            while((readch=fgetc(fp))!=EOF)
            {
                if(i<1024)
                {
                    buffer[i]=readch;
                    i++;
                }
                else
                {
                    i=0;
                    int n=send(con_socket, buffer, 1024, 0);
                    if(n==-1)
                    {
                        printf("Send File Error!\n");
                    }
                }
            }
            fclose(fp);
            printf("File:%s Transfer Finished!\n", file_name);
        }
        fclose(fp);
        long wordscount;
        recv(con_socket, &wordscount, sizeof(long), 0);
        printf("%ld\n", wordscount);
    }
    closesocket(con_socket);

    WSACleanup();
    return 0;
}
